package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityGeneralGoodsOfferListBinding;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.adapter.self.logistics.OfferOwnerGeneralAdapter;
import com.sgb.kjwl.viewmodel.self.logistics.OfferListGeneralGoodsModel;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * Describe:    普通货源报价（接单）单位列表
 * Author:  hl
 * Date:    2021/9/24
 */
@Route(path = AppRouteConstant.WuLui.ROUTER_PATH_OFFER_LIST_GENERAL_GOODS_ACTIVITY)
public class OfferListGeneralGoodsActivity extends AppActivity {
    private ActivityGeneralGoodsOfferListBinding binding;
    private OfferListGeneralGoodsModel viewModel;

    //报价列表数据适配器
    private OfferOwnerGeneralAdapter offerOwnerAdapter;


    //倒计时Bar是否有效
    private boolean isValid = false;
    private String goodsNo;
    private boolean mIsGeneral;

    public static void start(Context context, String sourceNo, boolean isGeneral) {
        Intent intent = new Intent(context, OfferListGeneralGoodsActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("no", sourceNo);
        intent.putExtra(RouterKey.BOOLEAN, isGeneral);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        goodsNo = getIntent().getStringExtra("no");
        mIsGeneral = getIntent().getBooleanExtra(RouterKey.BOOLEAN, true);
        binding = DataBindingUtil.setContentView(OfferListGeneralGoodsActivity.this, R.layout.activity_general_goods_offer_list);
        viewModel = new ViewModelProvider(this).get(OfferListGeneralGoodsModel.class);
        binding.closeAlter.setOnClickListener(this::onClick);
        binding.actionBar.setMenuIcon(R.drawable.wuliu_map_icon);
        binding.actionBar.setMenuClick(view -> OfferOwnerActivity.start(this, goodsNo));
        initAdapter();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);

        if (!TextUtils.isEmpty(goodsNo)) {
            viewModel.getOfferOwnerList(this, false, goodsNo, mIsGeneral);
        } else {
            finish();
        }

        viewModel.toastLiveData.observe(this, v -> MToast.showToast(this, v));
    }

    private void initAdapter() {
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        //首个列表页列表初始化
        if (offerOwnerAdapter == null) {
            offerOwnerAdapter = new OfferOwnerGeneralAdapter(this, null);
        }
        binding.recyclerView.setLayoutManager(layoutManager1);
        binding.recyclerView.setAdapter(offerOwnerAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.isMore.set(false);
                viewModel.getOfferOwnerList(OfferListGeneralGoodsActivity.this, false, goodsNo, mIsGeneral);
            }

            @Override
            public void onLoadMore() {
                viewModel.isMore.set(true);
                viewModel.getOfferOwnerList(OfferListGeneralGoodsActivity.this, true, goodsNo, mIsGeneral);
            }
        });
        offerOwnerAdapter.setOnItemClick(new AdapterOnItemClick<OrderQuoteEntity>() {
            @Override
            public void onItemClick(OrderQuoteEntity entity2, int position) {
                OfferOwnerDetailsActivity.start(getActivity(), entity2.getGoodsOfferNo(), true);
            }
        });
        offerOwnerAdapter.setonEditClick(entity -> viewModel.agreeOffer(this, entity.getGoodsOfferNo(), entity.getSourceNo()));

        viewModel.ldListOffer.observe(this, list -> showOfferOwner(list, viewModel.isMore.get()));
        viewModel.ldAgree.observe(this, a -> agreeOfferRefresh());
    }

    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.close_alter:
                binding.alterBar.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 刷新报价数据显示
     *
     * @param list
     * @param isMore
     */
    public void showOfferOwner(List<OrderQuoteEntity> list, boolean isMore) {
        if (list == null) {
            return;
        }
        if (isMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() != 0) {
                offerOwnerAdapter.addDatas(list);
            }
        } else {
            binding.recyclerView.refreshComplete();
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.alterBar.setVisibility(View.GONE);
                binding.recyclerView.setVisibility(View.GONE);
            } else {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
            }
            offerOwnerAdapter.setDatas(list);
        }

        if (list.size() > 0) {
            long shipmentEndTime = list.get(0).getShipmentEndTime();
            boolean isAgree = list.get(0).isAgree();
            if (isAgree) {
                isValid = false;
                binding.alterBar.setVisibility(View.GONE);
            } else {
                if (shipmentEndTime != 0) {
                    if (shipmentEndTime > System.currentTimeMillis()) {
                        //装货时间未结束
                        isValid = true;
                        binding.countdownDate.setText("您需要在" + DateUtils.formatDate(String.valueOf(shipmentEndTime), "yyyy年MM月dd日") + "前处理报价");
                        binding.alterBar.setVisibility(View.GONE);
                    } else {
                        isValid = false;
                        binding.alterBar.setVisibility(View.GONE);
                    }
                } else {
                    isValid = false;
                    binding.alterBar.setVisibility(View.GONE);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_OFFER_OWNER_PAGE) {
            viewModel.isMore.set(false);
            viewModel.getOfferOwnerList(this, false, goodsNo, mIsGeneral);
        }
    }

    /**
     * 货主同意了某条报价信息，需要刷新页面状态
     */
    public void agreeOfferRefresh() {
        viewModel.isMore.set(false);
        viewModel.getOfferOwnerList(this, false, goodsNo, mIsGeneral);
        EventBus.getDefault().post(LogisticsEvent.make(EventConstant.EVENT_GOODS_AGREED_OFFER, null));
    }
}
